/*
 *--------------------------------------------------------------------------
 *   Battlefield - A Realtime Network Multiplayer Game
 *   =======================================================
 *   Developed by Group D02 - 2009/2010 Semester 4 - CS2103
 *     Harry Nguyen Duy Hoang <nnduyhoang@yahoo.co.uk>
 *     Kent Chng Siang Rong <fivefootway@gmail.com>
 *     Lim Yong Peng <limpeng1986@gmail.com>
 *     Loh Xiankun <u0807185@nus.edu.sg>
 *   Instructed by
 *     Dr. Damith C.Rajapakse <damith@gmail.com>
 *   =======================================================
 *   $Id: RmiClient.java 568 2010-07-25 20:56:20Z Harry $
 *   $LastChangedDate: 2010-07-25 20:56:20 +0000 (Sun, 25 Jul 2010) $
 *   $LastChangedBy: Harry $
 *--------------------------------------------------------------------------
 */
package battlefield.net;

import battlefield.BattlefieldServerInterface;
import java.util.Properties;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;

/**
 *
 * @author xiankun
 */
public class RmiClient {

    private static final String LOOPBACK_IP_ADDRESS = "127.0.0.1";
    private static final String FACTORY = "java.naming.factory.initial";
    private static final String FACTORY_NAME = "com.sun.jndi.rmi.registry.RegistryContextFactory";
    private static final String PROVIDER = "java.naming.provider.url";
    private static String providerUrl = "rmi://";
    private String ipAddress;
    private BattlefieldServerInterface battlefieldServer;

    public RmiClient() {
        ipAddress = LOOPBACK_IP_ADDRESS;
    }

    public String getIpAddress() {
        return ipAddress;
    }

    public void setIpAddress(String ipAddress) {
        this.ipAddress = ipAddress;
    }

    public BattlefieldServerInterface getBattlefieldServerImp() {
        return battlefieldServer;
    }

    public void connectToHost() throws NamingException {
        try {
            //providerUrl = providerUrl + ipAddress + ":1099";
            Properties props = new Properties();
            props.put(RmiClient.FACTORY, RmiClient.FACTORY_NAME);
            props.put(RmiClient.PROVIDER, RmiClient.providerUrl + ipAddress + ":1099");
            InitialContext ic = new InitialContext(props);
            battlefieldServer = (BattlefieldServerInterface) PortableRemoteObject.narrow(ic.lookup("BattlefieldLogic"), BattlefieldServerInterface.class);
        } catch (NamingException ex) {
            throw new NamingException("Server not found");
        }
    }

    public void stopClient() {
        ipAddress = LOOPBACK_IP_ADDRESS;
        battlefieldServer = null;
    }
}
